// axios.util.js
(function(window) {
    // 创建axios实例
    const http = axios.create({
        baseURL: window.API_BASE_URL || '', // 从全局变量获取基础URL
        timeout: 10000,
        headers: { 'Content-Type': 'application/json' }
    });

    // 请求拦截器 - 添加认证token
    http.interceptors.request.use(config => {
        const token = localStorage.getItem('authToken');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    }, error => Promise.reject(error));

    // 响应拦截器 - 统一处理错误
    http.interceptors.response.use(
        response => response.data,
        error => {
            if (!error.response) {
                throw new Error('网络错误或服务不可达');
            }
            return Promise.reject(error.response.data);
        }
    );

    // 封装工具类方法
    const HttpService = {
        get(url, params = {}) {
            return http.get(url, { params });
        },

        post(url, data = {}, headers = {}) {
            return http.post(url, data, { headers });
        },
        // 同步 GET（使用 async/await 模拟）
        async getSync(url, params = {}) {
            try {
                const response = await http.get(url, { params });
                return response;
            } catch (error) {
                throw error; // 同步抛出错误
            }
        },

        // 同步 POST（使用 async/await 模拟）
        async postSync(url, data = {}, headers = {}) {
            try {
                const response = await http.post(url, data, { headers });
                return response;
            } catch (error) {
                throw error; // 同步抛出错误
            }
        },

        put(url, data = {}) {
            return http.put(url, data);
        },

        delete(url) {
            return http.delete(url);
        },

        upload(url, file, fieldName = 'file') {
            const formData = new FormData();
            formData.append(fieldName, file);
            return http.post(url, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
        },

        setBaseURL(baseURL) {
            http.defaults.baseURL = baseURL;
        }
    };

    // 挂载到全局对象
    window.HttpService = HttpService;

})(window);